package crawler.extension.ocr.service;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import crawler.extension.ocr.tool.PathTool;

@Service
public class FileService {

	private static Logger log = LoggerFactory.getLogger(FileService.class);

	@Autowired
	private PathTool pathTool;

	public Map<String, String> save(MultipartFile file, String website) {
		log.info("website : " + website);

		Map<String, String> configMap = pathTool.selectConfig(website);

		String path = configMap.get("filePath");
		log.info("path : " + path);

		Map<String, String> resultMap = new HashMap<String, String>();

		String type = null;// 文件类型
		
		if (file != null) {

			String fileName = file.getOriginalFilename();// 文件原名称
			System.out.println("上传的文件原名称:" + fileName);
			log.info("OriginalFilename : " + fileName);

			if (fileName.indexOf(".") != -1) {
				type = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length());
			}

			if (type == null) {
				fileName = fileName + ".jpg";
			}

			String trueFileName = String.valueOf(System.currentTimeMillis()) + fileName;
			// 设置存放图片文件的路径
			String filePath = path + trueFileName;
			System.out.println("存放图片文件的路径:" + filePath);
			log.info("FileName : " + trueFileName + " FilePath : " + filePath);

			File targetFile = new File(path, trueFileName);
			if (!targetFile.exists()) {
				targetFile.mkdirs();
			}
			
			// 转存文件到指定的路径
			try {
				file.transferTo(targetFile);
			} catch (IllegalStateException | IOException e) {
				e.printStackTrace();
				log.error("Save File Error : ",e);
				
				resultMap.put("result", "fail");
				return resultMap;
			}
			
			resultMap.put("result", "success");
			resultMap.put("resultMsg", "");
			resultMap.put("filePath", filePath);
			resultMap.put("fileName", trueFileName);
		} else {
			log.info("File is Null");
			
			resultMap.put("result", "fail");
			resultMap.put("resultMsg", "File is Null");
		}

		return resultMap;
	}
}
